export default {
  //为当前模块打开命名空间
  namespaced: true,
  //模块的state数据
  state: () => ({
    //购物车的数组，用来存储购物车中每个商品的信息对象
    //每个商品的信息对象，都应该包含下面6个属性：
    //{ goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
  }),
  //模块的mutations 方法
  mutations: {
    addToCart(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if (!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      this.commit('my_cart/saveToStore')
    },
    saveToStore(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    updateGoodsState(state, e) {
      const findResult = state.cart.find(x => x.goods_id === e.goods_id)
      if (findResult) {
        findResult.goods_state = e.goods_state
        this.commit('my_cart/saveToStore')
      }
    },
    updateAllGoodsState(state, newState) {
      state.cart.forEach(x => x.goods_state = newState)
      this.commit('my_cart/saveToStore')
    },
    updateGoodsCount(state, e) {
      const findResult = state.cart.find(x => x.goods_id === e.goods_id)
      if (findResult) {
        findResult.goods_count = e.goods_count
        this.commit('my_cart/saveToStore')
      }
    },
    removeGoods(state, goods_id) {
      state.cart = state.cart.filter(x => x.goods_id !== goods_id)
      this.commit('my_cart/saveToStore')
    }
  },
  //模块的getters属性
  getters: {
    //商品的数量
    total(state) {
      let c = 0
      state.cart.forEach(goods => c += goods.goods_count)
      return c
    },
    checkoutCount(state) {
      // 先使用 filter 方法，从购物车中过滤器已勾选的商品
      // 再使用 reduce 方法，将已勾选的商品总数量进行累加
      // reduce() 的返回值就是已勾选的商品的总数量;
      return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
    },
    checkoutPrice(state) {
      return state.cart.filter(x => x.goods_state)
                       .reduce((total, item) => total += item.goods_count * item.goods_price, 0)
                       .toFixed(2)
    }
  },
}
